//
//  OAuthViewController.swift
//  WeChat
//
//  Created by 梁迪 on 15/12/13.
//  Copyright © 2015年 梁迪. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    
    @objc private func defaultAccount(){
        let jsString = "document.getElementById('userId').value = 'liangdi1818@126.com' ,document.getElementById('passwd').value = 'Fuck12306'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    
    
    
    private func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
//    print(urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
        
        
        
    }
    
    
    private func setNavBar(){
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        
        
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
        setNavBar()
       
    }
    
    
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}







extension OAuthViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView:UIWebView){
        SVProgressHUD.show()
        
        
    }
    func webViewDidFinishLoad(webView:UIWebView){
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            
            
            return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com/"){
            
            return true
        }
        
        if !urlString.hasPrefix("http://www.baidu.com"){
            
            return false
        }
        
//        print(urlString)
        
        let query = request.URL?.query
        if let q = query {
            
            let codeStr = "code="
            let code = q.substringFromIndex(codeStr.endIndex)
//print(code)
            loadAccessToken(code)
        }
        
        
        return false
        
        
    }
    
    
    
    //加载用户token
    private func loadAccessToken(code:String){
       UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
        if isSuccess {
            print("登陆成功")
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "welcome")
            })
            
//            self.close()
        } else {
            print("登陆失败")
        }
        
        
        }
        
        
        
    }
    
    
//    private func loadAccessToken(code:String){
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
//        let AFN = AFHTTPSessionManager()
//        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        AFN.POST(urlString, parameters: parameters, progress: { (p) -> Void in
////            print("pppppppppp--------\(p)")
//            }, success: { (_, result) -> Void in
////                print("result--------\(result)")
//                if let dict = result as? [String : AnyObject]{
////                    let token = dict["access_token"] as! String
////                    let uid = dict["uid"] as! String
////                    self.loadUserInfo(token, uid: uid)
//                
//                    //字典转模型
//                    let userAccount = UserAccount(dict: dict )
////                    print("wwwwwwwww\(userAccount)")
//                    self.loadUserInfo(userAccount)
//                    
//                }
//                
//                
//            }) { (_, error) -> Void in
//                print("获取 token\(error)")
//        }
//        
//    }
//    
//    
//    private func loadUserInfo(userAccount:UserAccount){
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        if let token = userAccount.access_token, uid = userAccount.uid
//        
//        {
//        
//        let parameters = ["access_token":token,"uid":uid]
//        
//        let AFN = AFHTTPSessionManager()
//        AFN.GET(urlString, parameters: parameters, progress: { (p) -> Void in
////            print("pppppppppp--------\(p)")
//            }, success: { (_, result) -> Void in
////                print("result--------\(result)")
//                if let dict = result{
//                    
//                    let name = dict["name"] as!String
//                    let avatar_large = dict["avatar_large"] as!String
////                    print(name,avatar_large)
//                    
//                    userAccount.name = name
//                    userAccount.avatar_large = avatar_large
//                    userAccount.saveAccout()
//                }
//                
//                
//            }) { (_, error) -> Void in
//                print("获取用户信息\(error)")
//        }
//        
//        
//        
//        
//        
//        }
//        
//        
//    }
//    
    
}





